<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 聊天助手</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        #chat-box {
            border: 1px solid #ccc;
            height: 300px;
            overflow-y: scroll;
            padding: 10px;
            margin-bottom: 10px;
        }
        #user-input {
            width: 70%;
            padding: 8px;
        }
        #send-btn {
            padding: 8px 15px;
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        #clear-btn {
            padding: 8px 15px;
            background: #dc3545;
            color: white;
            border: none;
            cursor: pointer;
            margin-left: 10px;
        }
        .chat-controls {
            display: flex;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h1>AI 聊天助手 (连续对话模式)</h1>
    <div id="chat-box"></div>
    <input type="text" id="user-input" placeholder="输入你的问题..." />
    <div class="chat-controls">
        <button id="send-btn">发送</button>
        <button id="clear-btn">清除对话</button>
    </div>

    <script>
        const chatBox = document.getElementById("chat-box");
        const userInput = document.getElementById("user-input");
        const sendBtn = document.getElementById("send-btn");
        const clearBtn = document.getElementById("clear-btn");
        
        // 存储会话ID
        let sessionId = null;
        
        // 显示欢迎消息
        chatBox.innerHTML = `<p><strong>系统：</strong> 欢迎使用AI聊天助手，您可以开始对话了！</p>`;

        // 发送消息到后端API
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;

            // 显示用户消息
            chatBox.innerHTML += `<p><strong>你：</strong> ${message}</p>`;
            userInput.value = ""; // 清空输入框

            try {
                const response = await fetch("http://localhost:3001/chat", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ 
                        message,
                        sessionId
                    }),
                });

                // 从响应头中获取新的会话ID
                const newSessionId = response.headers.get('X-Session-Id');
                sessionId = newSessionId || sessionId;

                const data = await response.json();
                if (data.reply) {
                    chatBox.innerHTML += `<p><strong>AI：</strong> ${data.reply}</p>`;
                } else {
                    chatBox.innerHTML += `<p><strong>AI：</strong> 无法获取回复</p>`;
                }
            } catch (error) {
                chatBox.innerHTML += `<p><strong>错误：</strong> 请求失败</p>`;
                console.error("API调用失败:", error);
            }

            // 自动滚动到底部
            chatBox.scrollTop = chatBox.scrollHeight;
        }
        
        // 清除对话历史
        async function clearChat() {
            try {
                const response = await fetch("http://localhost:3001/clear-chat", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ sessionId }),
                });
                
                const data = await response.json();
                if (data.success) {
                    chatBox.innerHTML = `<p><strong>系统：</strong> 对话已清除，您可以开始新的对话！</p>`;
                }
            } catch (error) {
                console.error("清除对话失败:", error);
                chatBox.innerHTML += `<p><strong>错误：</strong> 清除对话失败</p>`;
            }
        }

        // 点击按钮或按 Enter 发送
        sendBtn.addEventListener("click", sendMessage);
        userInput.addEventListener("keypress", (e) => {
            if (e.key === "Enter") sendMessage();
        });
        
        // 清除对话按钮
        clearBtn.addEventListener("click", clearChat);
    </script>
</body>
</html>